
const jwt = require('jsonwebtoken')
const {TOKEN_KEY} = require('../config')
const author = async (ctx, next) => {
  const apiName = ctx.url
  if (apiName.indexOf('/api/') === -1) {
    await next()
  } else { 
    if (apiName === '/api/login' || apiName === '/api/signin' || apiName === '/api/test') {
      await next()
    } else {
      const token = ctx.request.headers["authorization"] 
      if (token) { 
      
        // 解析token
        const tokenData = jwt.verify(token, TOKEN_KEY) 
        const timeout = tokenData.timeout 
        const nowTime = new Date().getTime()
        
        if (nowTime > timeout) {
          ctx.body = {
            status: 403,
            message:'token 已过期，请重新登陆'
          } 
        } else {
          global.userInfo = {...tokenData}
          await next()
        }
      } else { 
        ctx.body = {
          status: 401,
          message:'没有token，没有权限'
        } 
      }  

    }
  }
    
}

module.exports = () => { return author }